import { createRouter, createWebHistory } from 'vue-router';
import { ElMessage } from 'element-plus';
import Department from '../views/Department.vue';
import Meeting from '../views/Meeting.vue';
import News from '../views/News.vue';
import Course from '../views/Course.vue';
import User from '../views/User.vue';
import Login from '../views/Login.vue';
import Tenant from '../views/Tenant.vue';
import Profile from '../views/Profile.vue';
import Register from '../views/Register.vue';

const routes = [
    {
        path: '/',
        redirect: '/news'
    },
    {
        path: '/login',
        component: Login,
        meta: { title: '登录' }
    },
    {
        path: '/user',
        component: User,
        meta: { title: '用户管理' }
    },
    {
        path: '/tenant',
        component: Tenant,
        meta: { title: '租户管理' }
    },
    {
        path: '/department',
        component: Department,
        meta: { title: '部门管理' }
    },
    {
        path: '/meeting',
        component: Meeting,
        meta: { title: '会议管理' }
    },
    {
        path: '/news',
        component: News,
        meta: { title: '新闻公告' }
    },
    {
        path: '/course',
        component: Course,
        meta: { title: '课程管理' }
    },
    {
        path: '/profile',
        component: Profile,
        meta: { title: '个人中心' }
    },
    {
        path: '/register',
        component: Register,
        meta: { title: '租户注册' }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

router.beforeEach((to, from, next) => {
    // 获取用户信息
    const currentUserStr = localStorage.getItem('currentUser');
    let userRole = null;
    if (currentUserStr) {
        try {
            userRole = JSON.parse(currentUserStr).userType;
        } catch {
            userRole = null;
        }
    }

    // userRole不为1的用户不能访问/department、/tenant、/user
    if (String(userRole) !== '2' && ['/department', '/tenant', '/user'].includes(to.path)) {
        ElMessage({
            message: '没有访问权限',
            type: 'warning',
        });

        next('/news');
        return;
    }

    // 允许访问
    next();
});

export default router; 